package com.example.server.plugins.routing

import com.example.commons.Ret
import com.example.commons.models.Article
import com.example.server.db.dao.ArticleDaoImpl
import io.ktor.http.*
import io.ktor.resources.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.resources.*
import io.ktor.server.resources.post
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.routing.put
import kotlinx.serialization.Serializable
import org.slf4j.Logger
import org.slf4j.LoggerFactory


private val logger: Logger = LoggerFactory.getLogger("Article")

fun Route.configArticleRouting() {

    get<Articles.Page> { article ->
        val lists = ArticleDaoImpl.getInstance().page(article.page, article.size)
        call.respond(lists)
    }

    post<Articles> {
        val newArticle = call.receive<Article>()
//        logger.info(newArticle.toString())
        val ar = ArticleDaoImpl.getInstance().addNewArticle(newArticle)
        call.respond(Ret<Article>(ar))
    }
    get<Articles.Id> { article ->
        val a = ArticleDaoImpl.getInstance().findWithUserById(article.id)
        call.respond(HttpStatusCode.OK, Ret<Article>(a))
    }
    put<Articles.Id> { article ->
        val newArticle = call.receive<Article>()
        newArticle.id = article.id
        val a = ArticleDaoImpl.getInstance().editArticle(newArticle)
        call.respond(HttpStatusCode.OK, Ret<Boolean>(a))
    }
    delete<Articles.Id> { article ->
        val re = ArticleDaoImpl.getInstance().deleteArticle(article.id)
        call.respond(HttpStatusCode.OK, Ret<Boolean>(re))
    }
}


@Serializable
@Resource("/articles")
private class Articles() {

    @Serializable
    @Resource("")
    data class Page(val page: Int = 1, val size: Int = 30)

    @Serializable
    @Resource("{id}")
    class Id(val parent: Articles = Articles(), val id: Long) {
//        @Serializable
//        @Resource("edit")
//        class Edit(val parent: Id)
    }
}